package com.itheima.controller;

import com.itheima.pojo.User;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * <dl>
 * <dd>描述: ~节点业务逻辑实现</dd>
 * <dd>创建时间：  14:36 2020/4/23</dd>
 * <dd>创建人： zz</dd>
 * <dt>版本历史: </dt>
 * <pre>
 * Date         Author      Version     Description
 * ------------------------------------------------------------------
 * 2020/4/23      guodong       1.0        1.0 Version
 * </pre>
 * </dl>
 */
@RestController
@RequestMapping("/consumer")
public class ConsumerController {

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private DiscoveryClient discoveryClient;

    @GetMapping("/findUserById/{id}")
    @HystrixCommand(fallbackMethod = "fallMethod")
    public User findUserById(@PathVariable("id") Integer id) {

        /*
            1.url硬编码(写死了)
            2.负载问题
            3.消费者无法感知生产者健康状态
         */

        //第一版：url硬编码
        // String url = "http://127.0.0.1:9091/user/findUserById/" + id;


        //第二版： 解决url硬编码问题
        //"uri": "http://localhost:9091",
        //1.获取服务列表
      /*  List<ServiceInstance> instances = discoveryClient.getInstances("provider-service");
        ServiceInstance serviceInstance = instances.get(0);
        //2.获取uri
        URI uri = serviceInstance.getUri();
        //3.url拼接
        String url = uri + "/user/findUserById/" + id;
        System.out.println("url拼接后： " + url);*/


        //第三版： 解决负载问题 根据服务应用名称来进行调用
        /*
            1.根据服务应用名称从注册中心获取服务列表
            2.根据获取到的服务列表进行负载算法挑选服务进行访问
         */
        String url = "http://provider-service/user/findUserById/" + id;
        User user = restTemplate.getForObject(url, User.class);
        return user;
    }


    /*
        默认熔断方法
        要求：
            1.返回数据类型必须与原方法一致
            2.入参必须与原方法一致
     */
    public User fallMethod(Integer id) {
        User user = new User();
        user.setId(id);
        user.setNote("~默认熔断方法~");
        return user;
    }

    /*
        获取服务列表信息
     */
    @GetMapping("/getServices")
    public List<ServiceInstance> getServices() {
        //"uri": "http://localhost:9091",
        List<ServiceInstance> instances = discoveryClient.getInstances("provider-service");
        return instances;
    }

}
